#include "ftpserverpanel.h"
#include "ui_ftpserverpanel.h"
#include <QtNetwork>
#include <QDebug>
#include <QDirModel>
#include <QListWidgetItem>
#include <QDir>
#include <QTextCodec>
#include <QFileDialog>
#include <QSettings>
#include <QMessageBox>
#include <QMenu>

FTPServerPanel::FTPServerPanel(QWidget *parent) :
    QWidget(parent),
    ui(new Ui::FTPServerPanel)
{
    ui->setupUi(this);
    server = new Server(this);
    ui->groupBox_CP->hide();
    ui->groupBox_Connected->hide();
    ui->btn_stopServer->setEnabled(false);
    LoadFtpConfig();
    getUsers();

    fileModel = new QFileSystemModel;
   // fileModel->setRootPath(QDir::currentPath());
    fileModel->setRootPath(ui->rootPath->text());

//    QStringList filter;
//        filter <<"*.hdr"<<"*.CON" <<"*.dat" <<"*.cfg" <<"*.zip";
//        fileModel->setNameFilters(filter);
        fileModel->setNameFilterDisables(false);

        ui->localFiles->setModel(fileModel);
        ui->localFiles->setRootIndex(fileModel->index(ui->rootPath->text()));
        ui->localFiles->setAnimated(false);
        ui->localFiles->setSortingEnabled(true);
        ui->localFiles->expandAll();

       ui->localFiles->setColumnWidth(0, 200);
       ui->localFiles->setColumnWidth(2, 80);
       ui->localFiles->setColumnWidth(3, 120);

    connect(server, SIGNAL(sendToLogServer(QString)), this, SLOT(appendLogServer(QString)));
    connect(server, SIGNAL(sendToLogClient(QString,QString)), SLOT(appendLogClient(QString, QString)));
    connect(server, SIGNAL(sendToTable(QString, QString, QString)), this, SLOT(appendTable(QString, QString, QString)));
    connect(server, SIGNAL(removeFromTableSignal(int)), this, SLOT(removeFromTable(int)));
    connect(this, SIGNAL(deleteUser(int)), server, SLOT(deleteUserServer(int)));
    connect(ui->connectedUsersTable, SIGNAL(customContextMenuRequested(const QPoint &)), this, SLOT(deleteUserMenu(const QPoint &)));

   //  setStandardSettings();

}

FTPServerPanel::~FTPServerPanel()
{
    delete ui;
    delete server;
}

void FTPServerPanel::deleteUserMenu(const QPoint &click){
    QMenu menu(this);
    QAction *u = menu.addAction(tr("Kick user"));
    QAction *a = menu.exec(ui->connectedUsersTable->viewport()->mapToGlobal(click));

    if(a == u){
        int selectedRow = ui->connectedUsersTable->selectionModel()->currentIndex().row();
        int selectedId = ui->connectedUsersTable->item(selectedRow, 0)->text().toInt();
        emit deleteUser(selectedId);
        ui->connectedUsersTable->removeRow(selectedRow);
    }
}

void FTPServerPanel::appendLogServer(QString msg){
    QDateTime current = QDateTime::currentDateTime();
    ui->log->appendPlainText(current.toString() + " - [SERVER] > " + msg);
}

void FTPServerPanel::appendLogClient(QString username, QString message){
   // qDebug()<<" MainWindow appendLogClient: username"<<username<<" message:"<<message;
    QDateTime current = QDateTime::currentDateTime();
    ui->log->appendPlainText(current.toString() + " - ["+username+"] > " + message.trimmed());
}

void FTPServerPanel::appendTable(QString id, QString ip, QString username){
    ui->connectedUsersTable->insertRow(ui->connectedUsersTable->rowCount());
    ui->connectedUsersTable->setItem(ui->connectedUsersTable->rowCount()-1, 0, new QTableWidgetItem(id));
    ui->connectedUsersTable->setItem(ui->connectedUsersTable->rowCount()-1, 1, new QTableWidgetItem(username));
    ui->connectedUsersTable->setItem(ui->connectedUsersTable->rowCount()-1, 2, new QTableWidgetItem(ip));
}


void FTPServerPanel::removeFromTable(int id){
    for(int i = 0; i < ui->connectedUsersTable->rowCount(); i++){
        if(ui->connectedUsersTable->item(i, 0)->text().toInt() == id){
            ui->connectedUsersTable->removeRow(i);
        }
    }
}


void FTPServerPanel::setStandardSettings(){
    QSettings settings;
    settings.setValue("serverPort", (settings.value("serverPort").isNull()) ? 1234 : settings.value("serverPort").toInt());
    settings.setValue("maxUsers", (settings.value("maxUsers").isNull()) ? 5 : settings.value("maxUsers").toInt());
    settings.setValue("rootPath", (settings.value("rootPath").isNull()) ? QDir::homePath() : settings.value("rootPath").toString());
    settings.setValue("welcomeMessage", (settings.value("welcomeMessage").isNull()) ? "Welcome to Jussie's FTP Server!" : settings.value("welcomeMessage").toString());
    settings.setValue("allowAnonUsers", (settings.value("allowAnonUsers").isNull()) ? false : settings.value("allowAnonUsers").toBool());
}



void FTPServerPanel::SaveFtpConfig()
{
    QString  dirPath =  QCoreApplication::applicationDirPath() +"/config/ftp.ini";
    if (!dirPath.isEmpty())
    {
        QFileInfo fileInfo(dirPath);
        if (fileInfo.exists()){
            QFile file(dirPath);
            file.remove();
        }
    }

    QSettings *settings = new QSettings(dirPath, QSettings::IniFormat);
     settings->beginGroup("Ftp");
     settings->setValue("serverPort",     ui->serverPort->text().toInt());
     settings->setValue("maxUsers",       ui->maxUsers->text().toInt());
     settings->setValue("rootPath",       ui->rootPath->text());
     settings->setValue("welcomeMessage", ui->welcomeMessage->text());
     settings->setValue("allowAnonUsers", ui->allowAnon->isChecked());
     settings->endGroup();

     fileModel = new QFileSystemModel;
    // fileModel->setRootPath(QDir::currentPath());
     fileModel->setRootPath(ui->rootPath->text());
//     QStringList filter;
//         filter <<"*.hdr"<<"*.CON" <<"*.dat" <<"*.cfg" <<"*.zip";
//         fileModel->setNameFilters(filter);
         fileModel->setNameFilterDisables(false);

         ui->localFiles->setModel(fileModel);
         ui->localFiles->setRootIndex(fileModel->index(ui->rootPath->text()));
         ui->localFiles->setAnimated(false);
         ui->localFiles->setSortingEnabled(true);
         ui->localFiles->expandAll();
}


void FTPServerPanel::LoadFtpConfig()
{
    QString  dirPath =  QCoreApplication::applicationDirPath() +"/config/ftp.ini";
    QSettings *settings = new QSettings(dirPath, QSettings::IniFormat);
     settings->beginGroup("Ftp");
     ui->serverPort->setText(    settings->value("serverPort","21").toString());
     ui->maxUsers->setValue(     settings->value("maxUsers",2).toInt());
     ui->rootPath->setText(      settings->value("rootPath","./").toString());
     ui->welcomeMessage->setText(settings->value("welcomeMessage","").toString());
     ui->allowAnon->setChecked(  settings->value("allowAnonUsers").toBool());

     settings->endGroup();

}

void FTPServerPanel::on_btn_UP_clicked()
{
    if(ui->groupBox_CP->isHidden())
    {
        ui->groupBox_CP->show();
       ui->btn_UP->setIcon(QPixmap(":/Images/Images/add_top_blue.png"));
    }
    else
    {
        ui->groupBox_CP->hide();
        ui->btn_UP->setIcon(QPixmap(":/Images/Images/add_bottom_blue.png"));
    }
}

void FTPServerPanel::on_btn_DN_clicked()
{
    if(ui->groupBox_Connected->isHidden())
    {
        ui->groupBox_Connected->show();
        ui->btn_DN->setIcon(QPixmap(":/Images/Images/add_bottom_blue.png"));
    }
    else
    {
        ui->groupBox_Connected->hide();
        ui->btn_DN->setIcon(QPixmap(":/Images/Images/add_top_blue.png"));
    }
}

void FTPServerPanel::on_saveButton_clicked()
{
   SaveFtpConfig();
}



void FTPServerPanel::load(){
    QFile file("users.txt");
    if(!file.open(QIODevice::ReadOnly)){
      //  qDebug() << "Error";
    } else {
        QDataStream in(&file);
        users.clear();
        in >> users;
    }

    file.flush();
    file.close();

}
void FTPServerPanel::getUsers()
{

    QFile file("users.us");
    QMap <QString, QString> users;

    if(!file.exists()){
        file.open(QIODevice::WriteOnly);
        file.close();
    }

    if(file.exists()){
        if(!file.open(QIODevice::ReadOnly)){
            qDebug() << "Error";
            return;
        } else {
            QDataStream in(&file);
            users.clear();
            in >> users;
            file.close();
        }
    }
 ui->userTable->clear();
 ui->userTable->setRowCount(0);
    QMap<QString, QString>::const_iterator i = users.constBegin();
    while( i != users.constEnd()){
        ui->userTable->insertRow(ui->userTable->rowCount());
        ui->userTable->setItem(ui->userTable->rowCount()-1, 0, new QTableWidgetItem(i.key()));
        ui->userTable->setItem(ui->userTable->rowCount()-1, 1, new QTableWidgetItem(i.value()));
        ++i;
    }
}

void FTPServerPanel::add(QString &username, QString &password){

    QFile file("users.us");

    if(!file.exists()){
        file.open(QIODevice::WriteOnly);
        file.close();
    }

    if(file.exists()){
        if(!file.open(QIODevice::ReadOnly)){
            qDebug() << "Error";
            return;
        } else {
            QDataStream in(&file);
            users.clear();
            in >> users;
        }

        file.flush();
        file.close();
    }

    if(!file.open(QIODevice::WriteOnly)){
        ui->message->setText("Something went wrong...");
        return;
    } else {
        if(!users.contains(username)){
            users.insert(username, password);
            QDataStream out(&file);
            out << users;
            ui->message->setText("New user added!");
        } else {
            ui->message->setText("User already exists...");
        }
    }

    file.flush();
    file.close();
}

void FTPServerPanel::on_addUserButton_clicked()
{
    QString username  = ui->userName->text();
    QString password  = ui->password->text();
    QString cPassword = ui->cPassword->text();

    if(username.isEmpty() || password.isEmpty() || cPassword.isEmpty()){
        ui->message->setText("Please enter all fields!");
    }else {
        if(password != cPassword){
            ui->message->setText("Passwords do not match!");
        } else {
            add(username, password);
        }
    }
    getUsers();
}

void FTPServerPanel::on_browseButton_clicked()
{
    QString dir = QFileDialog::getExistingDirectory(this, tr("Open Directory"),
                                                 QDir::homePath(),
                                                 QFileDialog::ShowDirsOnly
                                                 | QFileDialog::DontResolveSymlinks);
    ui->rootPath->setText(dir);
}

void FTPServerPanel::on_userTable_doubleClicked(const QModelIndex &index)
{

}

void FTPServerPanel::on_btn_startServer_clicked()
{
    appendLogServer("Starting server!");

     ui->btn_stopServer->setEnabled(true);
     ui->btn_startServer->setEnabled(false);
    if(NULL!=server){
      server->startServer();
    }
}

void FTPServerPanel::on_btn_stopServer_clicked()
{
    appendLogServer("Shutting down...");
    ui->btn_stopServer->setEnabled(false);
    ui->btn_startServer->setEnabled(true);
 if(NULL!=server)
 {
    server->stopServer();
 }
    ui->connectedUsersTable->setRowCount(0);
}
